package com.butterfly.webserver;

import java.io.*;
import java.net.Socket;

/**
 * Created by DouDou on 2016/9/20.
 */
public class Process extends Thread {

    private Socket socket;
    private BufferedReader in;
    private PrintStream out;
    private final String WEB_ROOT = "E:\\IT\\WorkSpace\\idea\\webserver\\src\\com\\butterfly\\webserver\\";

    public Process(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out  = new PrintStream(socket.getOutputStream());
            this.deal(in,out);
            in.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理请求
     * @param in
     * @param out
     */
    private void deal(BufferedReader in,PrintStream out) throws IOException {
        String line = in.readLine();
        String[] content = line.split(" ");
        if(content.length != 3){
            this.dealError(400,"query error!");
            return;
        }
        System.out.println("code:"+content[0]+"|fileName:"+content[1]+"|http version:"+content[2]);

        this.sendFile(content[1]);

        in.close();
        socket.close();
    }

    public void dealError(int code,String message){
        out.println("HTTP/1.0 " + code + " " +message);
        out.println("content-type:text/html;charset=UTF-8");
        //out.println("Charset:utf-8");
        out.println();
        out.println("<html>");
        out.println("<head>出错信息</head>");
        out.println("<body>");
        out.println("<h1>错误码："+ code + " 出错信息：" +message+ "</h1>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
        out.close();
    }

    public void sendFile(String fileName){
        String fn = fileName.substring(1);
        File file = new File(this.WEB_ROOT + fn);
        if(!file.exists()){
            this.dealError(404,"file not found!");
            return;
        }
        try{
            InputStream fin = new FileInputStream(file);
            byte[] content = new byte[(int)file.length()];
            fin.read(content);

            out.println("HTTP/1.0 200 "+fileName);
            out.println("content-length:"+content.length);
            out.println();
            out.write(content);
            out.flush();
            out.close();
            fin.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
